package com.kaka.bus.engine.home.info;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kaka.bus.R;
import com.kaka.bus.adapter.InfoAdapter;
import com.kaka.bus.base.fragment.BaseFragment;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.bean.NamePhoneBean;
import com.kaka.bus.bean.ProductDetailBean;
import com.kaka.bus.bean.Rolling;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.engine.HomeActivity;
import com.kaka.bus.engine.amount.gongjijinamount.GongJiJinActivity;
import com.kaka.bus.engine.amount.loanproduct.LoanProductActivity;
import com.kaka.bus.engine.home.info.amountlist.AmountActivity;
import com.kaka.bus.engine.home.info.card.CardListActivity;
import com.kaka.bus.engine.home.info.changepwd.ChangeActivity;
import com.kaka.bus.engine.home.info.message.MessageListActivity;
import com.kaka.bus.engine.home.info.opinion.OpinionActivity;
import com.kaka.bus.engine.home.info.question.QuestionActivity;
import com.kaka.bus.engine.home.info.self.SelfActivity;
import com.kaka.bus.engine.home.main.h5.H5Activity;
import com.kaka.bus.engine.user.login.LoginActivity;
import com.kaka.bus.listener.Listener;
import com.kaka.bus.util.HiddenAnimUtils;
import com.kaka.bus.util.U;
import com.kaka.bus.util.UserUtil;
import com.kaka.bus.view.InfoItemView;
import com.kaka.bus.view.dialog.TempletDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.Unbinder;

/**
 * Created by zhangqi on 2016/10/14.
 * e-mail : ${email}
 * desc :
 */

public class InfoFragment extends BaseFragment<InfoPresenter> implements InfoContract.View, InfoAdapter.InFoOnclick {


    @BindView(R.id.info_avatar)
    ImageView mInfoAvatar;
    @BindView(R.id.info_name)
    TextView mInfoName;
    @BindView(R.id.info_phone)
    TextView mInfoPhone;
    @BindView(R.id.info_card)
    TextView mInfoCard;
    @BindView(R.id.info_bill)
    TextView mInfoBill;
    @BindView(R.id.info_opinion)
    InfoItemView mInfoOpinion;
    @BindView(R.id.info_question)
    InfoItemView mInfoQuestion;
    @BindView(R.id.info_callus)
    InfoItemView mInfoCallus;
    @BindView(R.id.info_version)
    TextView mInfoVersion;
    @BindView(R.id.info_self)
    LinearLayout mInfoSelf;
    Unbinder unbinder;
    @BindView(R.id.info_changepwd)
    InfoItemView mInfoChangepwd;
    @BindView(R.id.info_msg)
    InfoItemView mInfoMsg;
    @BindView(R.id.info_recycler)
    RecyclerView infoRecycler;
    @BindView(R.id.info_finishRegist)
    InfoItemView mInfoFinishRegist;
    Unbinder unbinder1;
    private HomeActivity mHome;
    private InfoAdapter mAdapter;
    /**
     * 客服的电话结束
     */
    private String mPhone;
    private String mPhoneNet;
    private String followUsStr;
    private TempletDialog mFollowDialog;
    private Rolling mRolling;
    private boolean isclose = true;
    private List<ProductDetailBean> productBeans = new ArrayList<>();
    private ProductDetailBean mDefaultBean;
    private int recyclerHeight;

    public static InfoFragment getInstance(String value) {
        InfoFragment infoFragment = new InfoFragment();
        Bundle bundle = new Bundle();
        bundle.putString("value", value);
        infoFragment.setArguments(bundle);
        return infoFragment;
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();

        mRolling = UserUtil.getCache(UserUtil.SERVICE);
        if (mRolling != null) {
            mPhone = mRolling.getServiceCall();
            mPhoneNet = mRolling.getServiceCall();
            mPhone = mPhone.replaceAll("-", "");

            String workTime = mRolling.getWorkTime();
            if (!TextUtils.isEmpty(workTime)) {
                mInfoCallus.setTips(workTime);
            } else {
                mInfoCallus.setTips("周一至周五：9:00-18:00");
            }
        }

        if (!TextUtils.isEmpty(getUserId())) {
            mPresenter.loadNameAndPhone(getUserId(), getToken());
//            mPresenter.getRegistProduct(getUserId(), getToken());
        }

    }

    @Override
    protected void initData() {
//        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 4);
//        infoRecycler.setLayoutManager(gridLayoutManager);
//        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
//            @Override
//            public int getSpanSize(int position) {
//                if (mAdapter.isHeader(position)) {
//                    return gridLayoutManager.getSpanCount();
//                } else {
//                    return 1;
//                }
//            }
//        });
//
//        mAdapter = new InfoAdapter(getActivity(), this, productBeans);
//        infoRecycler.setAdapter(mAdapter);
//        mDefaultBean = new ProductDetailBean();
//        mDefaultBean.setProductType(-1);
    }

    @Override
    public void loadInfoSuccess(HttpWrapper<NamePhoneBean> wrapper) {
        if (Constant.SUCCESS_CODE.equals(wrapper.code)) {
            if ("y".equals(wrapper.data.getMsg())) {
//                mIvInfoNews.setImageResource(R.mipmap.account_icon_news);
            } else {
//                mIvInfoNews.setImageResource(R.mipmap.account_icon_new);
            }
            mInfoName.setText(wrapper.data.getName());
            mInfoPhone.setText(wrapper.data.getPhone());
            followUsStr = wrapper.data.getFollowUsStr();
        } else if (Constant.TOKEN_TIMEOUT.equals(wrapper.code)) {
            U.tokenOut(getActivity());
        } else {
            showMessage(wrapper.info);
        }
    }

    /**
     * @param bean code 202没有注册产品
     *             code 201接口异常
     */
    @Override
    public void registerProductSuccess(HttpWrapper<List<ProductDetailBean>> bean) {
        if (bean.code.equals("200")) {
            if (bean.getData() != null && bean.getData().size() > 0) {
                productBeans.clear();
                productBeans.addAll(bean.getData());
                mAdapter.notifyDataSetChanged();
            }

        } else if (bean.code.equals("202")) {
            productBeans.clear();
            productBeans.add(mDefaultBean);
            mAdapter.notifyDataSetChanged();
        } else {
            showMessage(bean.info);
            productBeans.clear();
            productBeans.add(mDefaultBean);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void doOnceOnFragmentLifecycle() {
        super.doOnceOnFragmentLifecycle();

        mFollowDialog = new TempletDialog.Builder(mActivity)
                .setLayout(R.layout.dialog_gzwm).setWidthPer(0.65).setMoveY(-50)
                .setWindowAnim(R.style.person＿dialog_anim).build();
    }

    private void call() {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mPhone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mHome = (HomeActivity) getActivity();
        mInfoFinishRegist.getInfoYou().setImageResource(R.drawable.question_up);
//        AppInfo appInfo = U.getAppInfo(mActivity);
//        mInfoVersion.setText(U.connectString("咔咔钱包 ", appInfo.getVersionName()));
//        mInfoVersion.setText(U.connectString("咔咔钱包"));
    }

    @Override
    protected void initListener() {
        mInfoOpinion.setOnClickListener(v -> startActivity(new Intent(getActivity(), OpinionActivity.class)));
        mInfoQuestion.setOnClickListener(v -> startActivity(new Intent(getActivity(), QuestionActivity.class)));
        mInfoBill.setOnClickListener(view -> startActivity(new Intent(getActivity(), AmountActivity.class)));
        mInfoCard.setOnClickListener(view -> startActivity(new Intent(getActivity(), CardListActivity.class)));
        mInfoCallus.setOnClickListener(v -> {
            if (TextUtils.isEmpty(mPhoneNet)) {
                return;
            }
            U.getSlectDialog(mHome, "温馨提示", "您将拨打 " + mPhoneNet, "取消", "呼叫", new Listener.OnNormalAlertDialogChooseClickListener() {

                @Override
                public void onLeft() {

                }

                @Override
                public void onRight() {
                    call();
                }
            }).show();
        });

        mInfoSelf.setOnClickListener(v -> {
            startActivity(new Intent(mActivity, SelfActivity.class));
        });

        mInfoChangepwd.setOnClickListener(v -> {
            startActivity(new Intent(mActivity, ChangeActivity.class));
        });

        mInfoMsg.setOnClickListener(v -> {
            startActivity(new Intent(mActivity, MessageListActivity.class));
        });
        mInfoFinishRegist.setOnClickListener(v -> {
//            if (isclose) {
//                infoRecycler.setVisibility(View.GONE);
//                isclose = false;
//                mInfoFinishRegist.getInfoYou().setImageResource(R.drawable.question_down);
//
//            } else {
//                infoRecycler.setVisibility(View.VISIBLE);
//                mInfoFinishRegist.getInfoYou().setImageResource(R.drawable.question_up);
//                isclose = true;
//            }
            if (infoRecycler.getHeight() > 30) {
                recyclerHeight = infoRecycler.getHeight();
            }
            HiddenAnimUtils.newInstance(getActivity(), infoRecycler, mInfoFinishRegist.getInfoYou(), recyclerHeight).toggle();

        });
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_info;
    }

    @Override
    public void onItemInfoClick(int position) {

        ProductDetailBean bean = productBeans.get(position);
        if (TextUtils.isEmpty(getUserId())) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
        } else {
            if (bean.getProductType() == 3) {
                startActivity(new Intent(getActivity(), GongJiJinActivity.class));
            } else {
                if (bean.getProductTypeCode().equals("pay_baika")) {
                    Intent mIntent = new Intent();
                    mIntent.setClass(getActivity(), H5Activity.class);
                    mIntent.putExtra(H5Activity.URL, bean.getRequestUrl());
                    startActivity(mIntent);
                } else {
                    Intent intent = new Intent(getActivity(), LoanProductActivity.class);
                    intent.putExtra(LoanProductActivity.MONEY, bean.getEstimatedAmount());
                    intent.putExtra(LoanProductActivity.PROID, bean.getProductId());

                    startActivity(intent);
                }
            }

        }

    }
}
